import React, { useEffect, useState } from 'react';
import { Steps, Form, Input, Select, Button, Modal } from 'antd';
import { getKvmNetworks, createVm } from '../api/virtApi';

const { Step } = Steps;

// 新增 formData 接口数据结构
interface FormData {
  name?: string;
  description?: string;
  memory?: string;
  vcpu?: string;
  threads?: string;
  cpuTopology?: string;
  disks?: Array<{
    type?: string;
    device?: string;
    driverName?: string;
    driverType?: string;
    size?: string;
    sourceFile?: string;
    targetDev?: string;
    bus?: string;
  }>;
  network?: string;
  osType?: string;
  iso?: string;
}

interface CreateVMModalProps {
  isModalVisible: boolean;
  handleModalOk: () => void;
  handleModalCancel: () => void;
  currentStep: number;
  setCurrentStep: (step: number) => void;
}

const CreateVMModal: React.FC<CreateVMModalProps> = ({ isModalVisible, handleModalOk, handleModalCancel, currentStep, setCurrentStep }) => {
  const [showAdvanced, setShowAdvanced] = React.useState(false); 
  const [formData, setFormData] = React.useState<FormData>({});
  const [expandedDisks, setExpandedDisks] = React.useState<{ [key: number]: boolean }>({});
  const [xmlContent, setXmlContent] = React.useState<string>(''); // 新增状态来存储XML内容
  const [networks, setNetworks] = useState<any[]>([]); // 存储网络信息

  useEffect(() => {
    const fetchNetworks = async () => {
      try {
        const result = await getKvmNetworks();
        setNetworks(result);
      } catch (error) {
        console.error('获取网络信息失败:', error);
      }
    };

    fetchNetworks();
    updateXmlContent();
  }, []);

  useEffect(() => {
    updateXmlContent();
  }, [formData]);

  const nextStep = () => {
    setCurrentStep(currentStep + 1);
  };

  const prevStep = () => {
    setCurrentStep(currentStep - 1);
  };

  const generateXML = () => {
    const { name, description, memory, vcpu, threads, cpuTopology, disks, network, osType, iso } = formData;
    let xml = `<domain type='kvm'>\n`;
    xml += `  <name>${name || 'example'}</name>\n`;
    if (description) {
      xml += `  <description>${description}</description>\n`;
    }
    xml += `  <memory unit='MiB'>${memory || '2048'}</memory>\n`;
    xml += `  <vcpu placement='static'>${vcpu || '2'}</vcpu>\n`;
    if (threads) {
      xml += `  <vcpu placement='static' threads='${threads}'>${vcpu || '2'}</vcpu>\n`;
    }
    if (cpuTopology) {
      xml += `  <cpu mode='host-model' check='partial'>\n`;
      xml += `    <topology sockets='${cpuTopology === 'socket' ? vcpu : 1}' cores='${cpuTopology === 'core' ? vcpu : 1}' threads='${cpuTopology === 'thread' ? threads : 1}'/>\n`;
      xml += `  </cpu>\n`;
    }
    xml += `  <os>\n`;
    xml += `    <type arch='x86_64' machine='pc-i440fx-focal'>${osType || 'hvm'}</type>\n`;
    xml += `    <boot dev='hd'/>\n`;
    xml += `  </os>\n`;
    xml += `  <devices>\n`;
    disks?.forEach((disk: any, index: number) => {
      xml += `    <disk type='${disk.type || 'file'}' device='${disk.device || 'disk'}'>\n`;
      xml += `      <driver name='${disk.driverName || 'qemu'}' type='${disk.driverType || 'qcow2'}'/>\n`;
      xml += `      <source file='${disk.sourceFile || '/path/to/image.qcow2'}'/>\n`;
      xml += `      <target dev='${disk.targetDev || 'vda'}' bus='${disk.bus || 'virtio'}'/>\n`;
      xml += `    </disk>\n`;
    });
    xml += `    <interface type='network'>\n`;
    xml += `      <source network='${network || 'default'}'/>\n`;
    xml += `      <model type='virtio'/>\n`;
    xml += `    </interface>\n`;

    // 添加 graphics 标签
    xml += `    <graphics type='spice' autoport='yes'>\n`;
    xml += `      <listen type='address' address='127.0.0.1'/>\n`;
    xml += `      <image compression='off'/>\n`;
    xml += `    </graphics>\n`;

    xml += `  </devices>\n`;
    xml += `</domain>`;
    return xml;
  };

  // 新增函数来更新XML内容
  const updateXmlContent = () => {
    const xml = generateXML();
    console.log('Generated XML:', xml); // 添加调试信息
    setXmlContent(xml);
  };

  // 新增函数来调用 createVm 接口
  const handleCreateVm = async () => {
    const xml = generateXML();
    try {
      await createVm(xml);
      console.log('虚拟机创建成功');
      handleModalOk();
    } catch (error) {
      console.error('虚拟机创建失败:', error);
    }
  };

  const steps = [
    {
      title: '基本信息',
      content: (
        <Form layout="vertical" style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Form.Item label="虚拟机名称" name="name" style={{ marginBottom: '12px', width: '500px' }}>
            <Input style={{ width: '100%', height: '40px', borderRadius: '4px' }} onChange={(e) => { setFormData({ ...formData, name: e.target.value }); updateXmlContent(); }}></Input>
          </Form.Item>
          <Form.Item label="描述" name="description" style={{ marginBottom: '12px', width: '500px' }}>
            <Input.TextArea
              style={{ width: '100%', minHeight: '100px', borderRadius: '4px' }}
              autoSize={{ minRows: 3, maxRows: 5 }}
              onChange={(e) => { setFormData({ ...formData, description: e.target.value }); updateXmlContent(); }}
            ></Input.TextArea>
          </Form.Item>
        </Form>
      ),
    },
    {
      title: '资源配置',
      content: (
        <Form layout="vertical" style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Form.Item label="内存大小(MB)" name="memory" style={{ marginBottom: '12px', width: '500px' }}>
            <Input
              type="number"
              style={{ width: '100%', height: '40px', borderRadius: '4px' }}
              onChange={(e) => { setFormData({ ...formData, memory: e.target.value }); updateXmlContent(); }}
            ></Input>
          </Form.Item>
          <Form.Item label="CPU核心数" name="vcpu" style={{ marginBottom: '12px', width: '500px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
              <Input
                type="number"
                style={{ width: '400px', height: '40px', borderRadius: '4px' }}
                onChange={(e) => { setFormData({ ...formData, vcpu: e.target.value }); updateXmlContent(); }}
              ></Input>
              <button
                style={{
                  color: '#1677ff',
                  cursor: 'pointer',
                  whiteSpace: 'nowrap',
                  lineHeight: '40px',
                  background: 'none',
                  border: 'none',
                  padding: 0
                }}
                onClick={() => setShowAdvanced(!showAdvanced)}
              >
                {showAdvanced ? '常规配置' : 'CPU特性配置'}
              </button>
            </div>
          </Form.Item>
          {showAdvanced && (
            <>
              <Form.Item label="CPU线程数" name="threads" style={{ marginBottom: '12px', width: '500px' }} initialValue={1}>
                <Input
                  type="number"
                  style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                  onChange={(e) => { setFormData({ ...formData, threads: e.target.value }); updateXmlContent(); }}
                ></Input>
              </Form.Item>
              <Form.Item label="CPU拓扑" name="cpuTopology" style={{ marginBottom: '12px', width: '500px' }}>
                <Select
                  style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                  dropdownStyle={{ borderRadius: '4px' }}
                  onChange={(value) => { setFormData({ ...formData, cpuTopology: value }); updateXmlContent(); }}
                >
                  <Select.Option value="default">默认</Select.Option>
                  <Select.Option value="socket">Socket</Select.Option>
                  <Select.Option value="core">Core</Select.Option>
                  <Select.Option value="thread">Thread</Select.Option>
                </Select>
              </Form.Item>
            </>
          )}
        </Form>
      ),
    },
    {
      title: '存储配置',
      content: (
        <Form layout="vertical" style={{ padding: '0 0px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Form.List name="disks">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => {
                  const isExpanded = expandedDisks[name] !== undefined ? expandedDisks[name] : true;

                  return (
                    <div key={key} style={{ width: '420px', marginBottom: '20px', border: '1px solid rgba(116, 116, 116, 0.87)', borderRadius: '4px', padding: '8px', backgroundColor: '#fff' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                        <span>磁盘配置 {name + 1}</span>
                        <Button type="link" onClick={() => setExpandedDisks({ ...expandedDisks, [name]: !isExpanded })}>
                          {isExpanded ? '收起' : '展开'}
                        </Button>
                      </div>
                      {isExpanded && (
                        <>
                          <div style={{ display: 'flex', gap: '20px', marginBottom: '8px' }}>
                            <Form.Item
                              {...restField}
                              label="磁盘类型"
                              name={[name, 'type']}
                              style={{ flex: 1 }}
                              initialValue="file"
                            >
                              <Select
                                style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                                dropdownStyle={{ borderRadius: '4px' }}
                                onChange={(value) => {
                                  const disks = formData.disks || [];
                                  disks[name] = { ...disks[name], type: value };
                                  setFormData({ ...formData, disks });
                                  updateXmlContent(); // 更新XML内容
                                }}
                              >
                                <Select.Option value="file">文件</Select.Option>
                                <Select.Option value="block">块设备</Select.Option>
                              </Select>
                            </Form.Item>
                            <Form.Item
                              {...restField}
                              label="设备类型"
                              name={[name, 'device']}
                              style={{ flex: 1 }}
                              initialValue="disk"
                            >
                              <Select
                                style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                                dropdownStyle={{ borderRadius: '4px' }}
                                onChange={(value) => {
                                  const disks = formData.disks || [];
                                  disks[name] = { ...disks[name], device: value };
                                  setFormData({ ...formData, disks });
                                  updateXmlContent(); // 更新XML内容
                                }}
                              >
                                <Select.Option value="disk">磁盘</Select.Option>
                                <Select.Option value="cdrom">光驱</Select.Option>
                              </Select>
                            </Form.Item>
                          </div>
                          <div style={{ display: 'flex', gap: '20px', marginBottom: '8px' }}>
                            <Form.Item
                              {...restField}
                              label="驱动名称"
                              name={[name, 'driverName']}
                              style={{ flex: 1 }}
                              initialValue="qemu"
                            >
                              <Input
                                style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                                onChange={(e) => {
                                  const disks = formData.disks || [];
                                  disks[name] = { ...disks[name], driverName: e.target.value };
                                  setFormData({ ...formData, disks });
                                  updateXmlContent(); // 更新XML内容
                                }}
                              ></Input>
                            </Form.Item>
                            <Form.Item
                              {...restField}
                              label="驱动类型"
                              name={[name, 'driverType']}
                              style={{ flex: 1 }}
                              initialValue="qcow2"
                            >
                              <Select
                                style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                                dropdownStyle={{ borderRadius: '4px' }}
                                onChange={(value) => {
                                  const disks = formData.disks || [];
                                  disks[name] = { ...disks[name], driverType: value };
                                  setFormData({ ...formData, disks });
                                  updateXmlContent(); // 更新XML内容
                                }}
                              >
                                <Select.Option value="qcow2">qcow2</Select.Option>
                                <Select.Option value="raw">raw</Select.Option>
                              </Select>
                            </Form.Item>
                          </div>
                          <Form.Item
                            {...restField}
                            label="磁盘大小(GB)"
                            name={[name, 'size']}
                            style={{ marginBottom: '8px' }}
                          >
                            <Input
                              type="number"
                              style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                              onChange={(e) => {
                                const disks = formData.disks || [];
                                disks[name] = { ...disks[name], size: e.target.value };
                                setFormData({ ...formData, disks });
                                updateXmlContent(); // 更新XML内容
                              }}
                            ></Input>
                          </Form.Item>
                          <Form.Item
                            {...restField}
                            label="源文件路径"
                            name={[name, 'sourceFile']}
                            style={{ marginBottom: '8px' }}
                          >
                            <Input
                              style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                              onChange={(e) => {
                                const disks = formData.disks || [];
                                disks[name] = { ...disks[name], sourceFile: e.target.value };
                                setFormData({ ...formData, disks });
                                updateXmlContent(); // 更新XML内容
                              }}
                            ></Input>
                          </Form.Item>
                          <div style={{ display: 'flex', gap: '20px', marginBottom: '8px' }}>
                            <Form.Item
                              {...restField}
                              label="目标设备"
                              name={[name, 'targetDev']}
                              style={{ flex: 1 }}
                              initialValue="vda"
                            >
                              <Input
                                style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                                onChange={(e) => {
                                  const disks = formData.disks || [];
                                  disks[name] = { ...disks[name], targetDev: e.target.value };
                                  setFormData({ ...formData, disks });
                                  updateXmlContent(); // 更新XML内容
                                }}
                              ></Input>
                            </Form.Item>
                            <Form.Item
                              {...restField}
                              label="总线类型"
                              name={[name, 'bus']}
                              style={{ flex: 1 }}
                              initialValue="virtio"
                            >
                              <Select
                                style={{ width: '100%', height: '40px', borderRadius: '4px' }}
                                dropdownStyle={{ borderRadius: '4px' }}
                                onChange={(value) => {
                                  const disks = formData.disks || [];
                                  disks[name] = { ...disks[name], bus: value };
                                  setFormData({ ...formData, disks });
                                  updateXmlContent(); // 更新XML内容
                                }}
                              >
                                <Select.Option value="virtio">virtio</Select.Option>
                                <Select.Option value="ide">ide</Select.Option>
                                <Select.Option value="scsi">scsi</Select.Option>
                              </Select>
                            </Form.Item>
                          </div>
                          <Button
                            type="dashed"
                            onClick={() => remove(name)}
                            style={{ width: '100%', height: '40px' }}
                          >
                            移除该磁盘
                          </Button>
                        </>
                      )}
                    </div>
                  );
                })}
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px', marginTop: '16px' }}>
                  <Button
                    type="dashed"
                    onClick={() => add({ type: 'file', device: 'disk', driverName: 'qemu', driverType: 'qcow2', size: '', sourceFile: '', targetDev: 'vda', bus: 'virtio' })}
                    style={{ width: '500px', height: '40px' }}
                  >
                    新建磁盘
                  </Button>
                  <Button
                    type="dashed"
                    onClick={() => add({ type: 'block', device: 'disk', driverName: 'qemu', driverType: 'raw', size: '', sourceFile: '', targetDev: 'vda', bus: 'virtio' })}
                    style={{ width: '500px', height: '40px' }}
                  >
                    选择本地磁盘
                  </Button>
                </div>
              </>
            )}
          </Form.List>
        </Form>
      ),
    },
    {
      title: '网络配置',
      content: (
        <Form layout="vertical" style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Form.Item label="网络类型" name="network" style={{ marginBottom: '12px', width: '500px' }}>
            <Select
              style={{ width: '100%', height: '40px', borderRadius: '4px' }}
              dropdownStyle={{ borderRadius: '4px' }}
              onChange={(value) => { setFormData({ ...formData, network: value }); updateXmlContent(); }}
            >
              {networks.map((network) => (
                <Select.Option key={network.name} value={network.name}>
                  {network.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      ),
    },
    {
      title: '操作系统',
      content: (
        <Form layout="vertical" style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Form.Item label="操作系统类型" name="osType" style={{ marginBottom: '12px', width: '500px' }}>
            <Select
              style={{ width: '100%', height: '40px', borderRadius: '4px' }}
              dropdownStyle={{ borderRadius: '4px' }}
              onChange={(value) => { setFormData({ ...formData, osType: value }); updateXmlContent(); }}
            >
              <Select.Option value="hvm">全虚拟化</Select.Option>
              <Select.Option value="xen">Xen</Select.Option>
              <Select.Option value="linux">Linux</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="ISO镜像" name="iso" style={{ marginBottom: '12px', width: '500px' }}>
            <Select
              style={{ width: '100%', height: '40px', borderRadius: '4px' }}
              dropdownStyle={{ borderRadius: '4px' }}
              onChange={(value) => { setFormData({ ...formData, iso: value }); updateXmlContent(); }}
            >
              <Select.Option value="centos">CentOS</Select.Option>
              <Select.Option value="ubuntu">Ubuntu</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      ),
    },
  ];

  return (
    <div style={{ display: 'flex' }}>
      <Modal
        title={
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <span style={{ color: '#1677ff' }}>配置虚拟机</span>
            <Steps
              current={currentStep}
              style={{
                width: '100%',
                whiteSpace: 'nowrap'
              }}
              size="small"
              onChange={(current) => setCurrentStep(current)}
            >
              {steps.map((step) => (
                <Step
                  key={step.title}
                  title={step.title}
                  style={{
                    flexShrink: 0,
                  }}
                />
              ))}
            </Steps>
          </div>
        }
        visible={isModalVisible}
        onCancel={handleModalCancel}
        width={1200}
        footer={null}
        bodyStyle={{ maxHeight: '70vh', display: 'flex' }}
      >
        <div style={{
          padding: '24px',
          backgroundColor: '#fff',
          borderRadius: '8px',
          boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
          margin: '0 24px',
          overflowY: 'auto',
          flex: 1,
          maxHeight: '70vh'
        }}>
          {steps[currentStep].content}
          <div style={{
            padding: '9px 0 0 0',
            textAlign: 'right',
          }}>
            {[
              currentStep > 0 && (
                <Button key="prev" onClick={prevStep}>
                  上一步
                </Button>
              ),
              currentStep < steps.length - 1 ? (
                <Button key="next" type="primary" onClick={nextStep}>
                  下一步
                </Button>
              ) : (
                <Button key="submit" type="primary" onClick={handleCreateVm}>
                  完成
                </Button>
              ),
            ]}
          </div>
        </div>
        <div style={{ width: '50%', padding: '2px', backgroundColor: '#f0f2f5', height: '100%', overflow: 'auto', maxHeight: '58vh' }}>
          <textarea
            value={xmlContent}
            style={{ width: 'calc(100% - 8px)', height: '70vh', borderRadius: '4px', padding: '2px', fontFamily: 'monospace' }}
            readOnly
          />
        </div>
      </Modal>
    </div>
  );
};

export default CreateVMModal;